package com.ukefu.webim.web.handler.apps.setting;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.Menu;
import com.ukefu.util.sensitive.SensitiveFilter;
import com.ukefu.webim.service.repository.SensitiveWordRepository;
import com.ukefu.webim.web.handler.Handler;
import com.ukefu.webim.web.model.SensitiveWord;

@Controller
@RequestMapping("/setting/sensitive")
public class SensitiveWordController extends Handler{
	
	@Autowired
	private SensitiveWordRepository sensitiveWordRes ;
	
	@RequestMapping("/agent/index")
	@Menu(type = "setting" , subtype = "sensitiveagent" )
	public ModelAndView agentindex(ModelMap map , HttpServletRequest request ,@Valid String msg){
		final String orgi = super.getOrgi(request);
		map.addAttribute("sensitivewordList", sensitiveWordRes.findAll(new Specification<SensitiveWord>(){
			@Override
			public Predicate toPredicate(Root<SensitiveWord> root, CriteriaQuery<?> query,CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();  
				
				list.add(cb.equal(root.get("orgi").as(String.class), orgi)) ;
				list.add(cb.equal(root.get("type").as(String.class), UKDataContext.SensitiveWordType.AGENT.toString())) ;
				
				Predicate[] p = new Predicate[list.size()];  
			    return cb.and(list.toArray(p));   
			}
		},new PageRequest(super.getP(request), super.getPs(request), Direction.DESC , "createtime"))) ;
		map.addAttribute("type", UKDataContext.SensitiveWordType.AGENT.toString()) ;
		map.addAttribute("msg", msg) ;
	    return request(super.createAppsTempletResponse("/apps/setting/sensitiveword/index"));
	}
	
	@RequestMapping("/user/index")
	@Menu(type = "setting" , subtype = "sensitiveuser" )
	public ModelAndView userindex(ModelMap map , HttpServletRequest request,@Valid String msg){
		final String orgi = super.getOrgi(request);
		map.addAttribute("sensitivewordList", sensitiveWordRes.findAll(new Specification<SensitiveWord>(){
			@Override
			public Predicate toPredicate(Root<SensitiveWord> root, CriteriaQuery<?> query,CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();  
				
				list.add(cb.equal(root.get("orgi").as(String.class), orgi)) ;
				list.add(cb.equal(root.get("type").as(String.class), UKDataContext.SensitiveWordType.USER.toString())) ;
				
				Predicate[] p = new Predicate[list.size()];  
			    return cb.and(list.toArray(p));   
			}
		},new PageRequest(super.getP(request), super.getPs(request), Direction.DESC , "createtime"))) ;
		map.addAttribute("type", UKDataContext.SensitiveWordType.USER.toString()) ;
		map.addAttribute("msg", msg) ;
	    return request(super.createAppsTempletResponse("/apps/setting/sensitiveword/index"));
	}
		
	@RequestMapping("/add")
	@Menu(type = "setting" , subtype = "sensitive" )
	public ModelAndView add(ModelMap map , HttpServletRequest request ,@Valid String type){
		map.addAttribute("type", type) ;
	    return request(super.createRequestPageTempletResponse("/apps/setting/sensitiveword/add"));
	}
	
	@RequestMapping("/save")
	@Menu(type = "setting" , subtype = "sensitive" )
	public ModelAndView save(ModelMap map , HttpServletRequest request ,@Valid SensitiveWord sensitiveword,@Valid String type){
		String msg = "" ;
		String word = sensitiveword.getKeyword().replaceAll(" ", "") ;
		if(!StringUtils.isBlank(word) && sensitiveWordRes.countByKeywordAndTypeAndOrgi(word, type, super.getOrgi(request)) == 0) {
			sensitiveword.setKeyword(word);
			sensitiveword.setCreater(super.getUser(request).getId());
			sensitiveword.setCreatetime(new Date());
			sensitiveword.setOrgi(super.getOrgi(request));
			sensitiveWordRes.save(sensitiveword) ;
			/**
	    	 * 初始化敏感词词库
	    	 */
	    	SensitiveFilter.getSensitiveFilter().inittSensitiveWords(super.getOrgi(request));
		}else {
			msg = "word_exist";
		}
		
		map.addAttribute("type", type) ;
	    return request(super.createRequestPageTempletResponse("redirect:/setting/sensitive/"+type+"/index.html?msg="+msg));
	}
	
	@RequestMapping("/batadd")
	@Menu(type = "setting" , subtype = "sensitive" )
	public ModelAndView batadd(ModelMap map , HttpServletRequest request ,@Valid String type){
		map.addAttribute("type", type) ;
	    return request(super.createRequestPageTempletResponse("/apps/setting/sensitiveword/batadd"));
	}
	
	@RequestMapping("/batadd/save")
	@Menu(type = "setting" , subtype = "sensitive" )
	public ModelAndView bataddsave(ModelMap map , HttpServletRequest request ,@Valid String content,@Valid String type){
		String msg = "" ;
		List<SensitiveWord> sensitiveWordList = new ArrayList<SensitiveWord>() ;
		if (!StringUtils.isBlank(content)) {
			for(String word : content.split("[, ，:；;\\n\t ]")){
				if(!StringUtils.isBlank(word)){
					SensitiveWord sensitiveword = new SensitiveWord();
					sensitiveword.setKeyword(word);
					sensitiveword.setType(type);
					sensitiveword.setCreater(super.getUser(request).getId());
					sensitiveword.setCreatetime(new Date());
					sensitiveword.setOrgi(super.getOrgi(request));
					sensitiveWordList.add(sensitiveword) ;
				}
			}
			if (sensitiveWordList.size() > 0) {
				sensitiveWordRes.save(sensitiveWordList) ;
				/**
		    	 * 初始化敏感词词库
		    	 */
		    	SensitiveFilter.getSensitiveFilter().inittSensitiveWords(super.getOrgi(request));
			}
		}
		
		map.addAttribute("type", type) ;
	    return request(super.createRequestPageTempletResponse("redirect:/setting/sensitive/"+type+"/index.html?msg="+msg));
	}
	
	@RequestMapping("/edit")
	@Menu(type = "setting" , subtype = "sensitive" )
	public ModelAndView edit(ModelMap map , HttpServletRequest request ,@Valid String type,@Valid String id){
		if (!StringUtils.isBlank(id)) {
			SensitiveWord sensitiveWord = sensitiveWordRes.findByIdAndOrgi(id, super.getOrgi(request)) ;
			map.addAttribute("sensitiveWord", sensitiveWord) ;
		}
		map.addAttribute("type", type) ;
	    return request(super.createRequestPageTempletResponse("/apps/setting/sensitiveword/edit"));
	}
	
	@RequestMapping("/update")
	@Menu(type = "setting" , subtype = "sensitive" )
	public ModelAndView update(ModelMap map , HttpServletRequest request ,@Valid SensitiveWord sensitiveword,@Valid String type){
		String msg = "" ;
		String word = sensitiveword.getKeyword().replaceAll(" ", "") ;
		if (!StringUtils.isBlank(sensitiveword.getId()) && !StringUtils.isBlank(word)) {
			SensitiveWord sensitiveWord = sensitiveWordRes.findByIdAndOrgi(sensitiveword.getId(), super.getOrgi(request)) ;
			if (!word.equals(sensitiveWord.getKeyword())) {
				if (sensitiveWordRes.countByKeywordAndTypeAndOrgi(word, type, super.getOrgi(request))==0) {
					if(!StringUtils.isBlank(word) ) {
						sensitiveWord.setKeyword(word);
						sensitiveWord.setPartofspeech(sensitiveword.getPartofspeech());
						sensitiveWord.setUpdatetime(new Date());
						sensitiveWordRes.save(sensitiveWord) ;
					}
				}else {
					msg = "word_exist";
				}
			}else {
				sensitiveWord.setPartofspeech(sensitiveword.getPartofspeech());
				sensitiveWord.setUpdatetime(new Date());
				sensitiveWordRes.save(sensitiveWord) ;
			}
			/**
	    	 * 初始化敏感词词库
	    	 */
	    	SensitiveFilter.getSensitiveFilter().inittSensitiveWords(super.getOrgi(request));
		}
		
	    return request(super.createRequestPageTempletResponse("redirect:/setting/sensitive/"+type+"/index.html?msg="+msg));
	}
	
	@RequestMapping("/delete")
	@Menu(type = "setting" , subtype = "sensitive" )
	public ModelAndView delete(HttpServletRequest request, @Valid String id, @Valid String type) {
		String msg = "" ;
		if (StringUtils.isNotBlank(id)) {
			SensitiveWord sensitiveWord = sensitiveWordRes.findByIdAndOrgi(id, super.getOrgi(request)) ;
			if (sensitiveWord!=null) {
				sensitiveWordRes.delete(sensitiveWord);
				/**
		    	 * 初始化敏感词词库
		    	 */
		    	SensitiveFilter.getSensitiveFilter().inittSensitiveWords(super.getOrgi(request));
			}
		}
	    return request(super.createRequestPageTempletResponse("redirect:/setting/sensitive/"+type+"/index.html?msg="+msg));
	}
	
	@RequestMapping("/batdel")
	@Menu(type = "setting" , subtype = "sensitive" )
	public ModelAndView batdel(ModelMap map, HttpServletRequest request, @Valid String[] ids, @Valid String type) {
		String msg = "";
		if(ids!=null && ids.length>0){
			List<SensitiveWord> list = sensitiveWordRes.findByOrgiAndIdIn(super.getOrgi(request),Arrays.asList(ids));
			if(list != null && list.size() > 0){
				sensitiveWordRes.delete(list);
			}

    		/**
        	 * 初始化敏感词词库
        	 */
        	SensitiveFilter.getSensitiveFilter().inittSensitiveWords(super.getOrgi(request));
    	}
		
		return request(super.createRequestPageTempletResponse("redirect:/setting/sensitive/"+type+"/index.html?msg="+msg));
	}
}
